<template>
	<a-card
		:bordered="false"
		:loading="cardLoading"
		class="xn-start-process-card"
		:tab-list="cardTabList"
		:active-tab-key="activeKey"
		@tabChange="cardChange"
	>
		<div v-if="activeKey === 'flowForm' && showPage">
			<div>
				<span class="left-span-label">填写表单</span>
				<p />
				<snowy-form-build
					v-if="recordData.formType === 'DESIGN'"
					ref="formBuildRef"
					:value="jsonData"
					:config="formConfig"
				/>
				<component
					v-else-if="recordData.formType === 'DEFINE'"
					ref="customFormRef"
					:is="customFormsLayouts"
					:value="initiatorDataJson"
				/>
				<div v-else>
					<a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" description="流程表单类型不正确，请联系管理员重置流程。" />
				</div>
				<div v-if="showLineChart">
					<span class="left-span-label">自选审批人</span>
					<a-card :bordered="false">
						<line-chart
							ref="lineChartRef"
							:model-design-data="modelDesignData"
							:org-tree-api="selectorApiFunction.orgTreeApi"
							:user-page-api="selectorApiFunction.userPageApi"
							:role-page-api="selectorApiFunction.rolePageApi"
							:org-page-api="selectorApiFunction.orgPageApi"
							:position-page-api="selectorApiFunction.positionPageApi"
						/>
					</a-card>
				</div>
			</div>
			<div v-if="showPage" class="pt-3 xn-start-process-button">
				<a-spin :spinning="buttonSpinning">
					<a-space>
						<a-button @click="onClose">
							<RollbackOutlined />
							返回
						</a-button>
						<span v-for="button in buttonInfo" :key="button.key">
							<a-button
								:type="button.type"
								:danger="button.type === 'danger'"
								@click="buttonClick(button.key)"
								v-if="button.value === 'SHOW'"
							>
								<template #icon>
									<component :is="button.icon" />
								</template>
								{{ button.label }}
							</a-button>
						</span>
					</a-space>
				</a-spin>
			</div>
		</div>
		<div v-else-if="activeKey === 'flowChart' && showPage">
			<flowChart v-model="modelDesignData" />
		</div>
		<div v-else>
			<a-result status="warning" title="警告" subTitle="对不起，您访问的数据未初始化成功。">
				<template #extra>
					<a-button type="primary" @click="onClose">返回上一页</a-button>
				</template>
			</a-result>
		</div>
		<userPosSelector ref="userPosSelectorRef" @ok="userPosChange" />
	</a-card>
</template>

<script setup name="newProcess">
	import { message, Empty } from 'ant-design-vue'
	import { nextTick } from 'vue'
	import tool from '@/utils/tool'
	import processMyApi from '@/api/flw/processMyApi'
	import taskApi from '@/api/flw/taskApi'
	import userCenterApi from '@/api/sys/userCenterApi'
	import FlowChart from '@/components/XnWorkflow/chart/index.vue'
	import UserPosSelector from './userPosSelector.vue'
	import workFlowUtils from '@/components/XnWorkflow/nodes/utils/index'
	import { loadComponent } from '@/components/XnWorkflow/customForm'
	import { isEmpty, cloneDeep } from 'lodash-es'
	import { useRoute, useRouter } from 'vue-router'
	const customFormRef = ref()
	const customFormsLayouts = ref()
	const route = useRoute()
	const router = useRouter()
	const token = tool.data.get('TOKEN')
	const lineChartRef = ref()
	const formConfig = ref({
		uploadFileHeaders: { token: token }, // 上传文件请求头部
		uploadImageHeaders: { token: token }, // 上传图片请求头部
		getOrgTree: (param) => {
			return taskApi.taskOrgTreeSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		getUserPage: (param) => {
			return taskApi.taskUserSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		}
	})
	// 选中的tab
	const activeKey = ref('flowForm')
	const nodeData = ref()
	// 模型设计器的值
	const modelDesignData = ref({})
	const jsonData = ref([])
	const formBuildRef = ref()
	const cardLoading = ref(false)
	const showPage = ref(false)
	const emit = defineEmits({ successful: null })

	// 职位选择ref定义
	const userPosSelectorRef = ref()
	const formData = ref({})
	const buttonInfo = ref()
	const buttonSpinning = ref(false)
	const recordData = ref()
	const buttonType = ref()
	const openType = ref()
	const draftId = ref()
	const showLineChart = ref(false)
	// json数据
	const initiatorDataJson = ref()
	const cardTabList = [
		{
			key: 'flowForm',
			tab: '表单'
		},
		{
			key: 'flowChart',
			tab: '流程图'
		}
	]
	onMounted(() => {
		if (isEmpty(route.query.modelId) || isEmpty(route.query.type)) {
			return
		}
		openType.value = route.query.type
		// 通过模型ID查询模型信息
		const param = {
			id: route.query.modelId
		}
		cardLoading.value = true
		processMyApi
			.processModelDetail(param)
			.then((record) => {
				nextTick(() => {
					showPage.value = true
				})
				recordData.value = record
				modelDesignData.value = JSON.parse(record.processJson)
				showLineChart.value = record.processJson.includes('CUSTOM') > 0 && record.processJson.includes('selectMode') > 0
				const thisNode = JSON.parse(record.processJson).childNode.childNode
				nodeData.value = thisNode
				buttonInfo.value = thisNode.properties.buttonInfo
				if (record.formType === 'DESIGN') {
					if (thisNode.properties.fieldInfo.length === 0 || thisNode.properties.buttonInfo.length === 0) {
						message.warning('该节点按钮与字段配置不正确，请联系管理员')
						return
					}
					// 转换数据
					jsonData.value = workFlowUtils.convSettingsField(JSON.parse(record.formJson), thisNode.properties.fieldInfo)
					if (record.dataJson) {
						const formData = Object.values(JSON.parse(record.dataJson))[0]
						nextTick(() => {
							setTimeout(() => {
								// 设置表单参数
								formBuildRef.value.setData(formData)
							}, 200)
						})
					}
				} else if (record.formType === 'DEFINE') {
					if (thisNode.properties.buttonInfo.length === 0) {
						message.warning('该节点按钮配置不正确，请联系管理员')
						return
					}
					if (!thisNode.properties.formInfo) {
						message.warning('该节点未配置表单，请联系管理员')
						return
					}
					const startTaskForm = thisNode.properties.formInfo.find((f) => f.key === 'FORM_URL').value
					customFormsLayouts.value = loadComponent(startTaskForm)
					if (record.dataJson) {
						initiatorDataJson.value = JSON.parse(record.dataJson)
					}
				}
			})
			.catch(() => {
				onClose()
			})
			.finally(() => {
				cardLoading.value = false
			})
	})
	// 卡片切换
	const cardChange = (key) => {
		activeKey.value = key
	}
	// 返回
	const onClose = () => {
		initiatorDataJson.value = {}
		recordData.value = {}
		router.go(-1)
	}
	// 点击按钮
	const buttonClick = (key) => {
		buttonType.value = key
		getFormDataAndSubmit()
	}
	// 验证并提交数据
	const getFormDataAndSubmit = () => {
		if (recordData.value.formType === 'DESIGN') {
			formBuildRef.value
				.getData()
				.then((values) => {
					formData.value = values
					if (buttonType.value === 'SUBMIT') {
						loadPos()
					} else {
						saveDraft()
					}
				})
				.catch(() => {})
		} else {
			customFormRef.value
				.getData()
				.then((values) => {
					formData.value = values
					if (buttonType.value === 'SUBMIT') {
						loadPos()
					} else {
						saveDraft()
					}
				})
				.catch(() => {})
		}
	}
	// 加载职位信息，如果只有一个职位，那么我们不让弹窗直接选中
	const loadPos = () => {
		buttonSpinning.value = true
		userCenterApi
			.userLoginPositionInfo()
			.then((data) => {
				if (isEmpty(data)) {
					message.warning('发起失败：未获得职位信息！')
					return
				}
				if (data.length === 1) {
					// 拿到主职位信息，直接发起
					startProcess(data[0])
				} else {
					// 打开职位选择，让其选择以哪个职位发起
					userPosSelectorRef.value.onOpen(data)
				}
			})
			.finally(() => {
				buttonSpinning.value = false
			})
	}
	// 保存草稿
	const saveDraft = () => {
		// 拼接JSON
		const param = {
			title: recordData.value.name,
			dataJson: JSON.stringify(formData.value)
		}
		if (openType.value === 'NEW') {
			param.modelId = recordData.value.id
		}
		// 草稿再保存
		if (openType.value === 'DRAFT') {
			param.modelId = recordData.value.modelId
			param.id = recordData.value.id
		}
		buttonSpinning.valueOf = true
		processMyApi
			.processSaveDraft(param)
			.then(() => {
				if (openType.value === 'DRAFT') {
					// 如果是草稿打开的，我们给其一个回调让刷新去
					emit('successful')
				}
				onClose()
			})
			.finally(() => {
				buttonSpinning.valueOf = false
			})
	}
	// 直接发起
	const startProcess = (record) => {
		try {
			// 这里开始就打loading，以免看着点下去没反应
			buttonSpinning.valueOf = true
			const userInfo = tool.data.get('USER_INFO')
			// 拼接JSON
			const param = {
				modelId: recordData.value.id,
				dataJson: JSON.stringify(formData.value),
				initiator: userInfo.id,
				initiatorName: userInfo.name,
				initiatorOrgId: record.orgId,
				initiatorOrgName: record.orgName,
				initiatorPositionId: record.positionId,
				initiatorPositionName: record.positionName
			}
			// 发起人自选列表的审批人
			if (showLineChart.value) {
				const selectData = cloneDeep(lineChartRef.value.getDataInfo())
				if (isEmpty(selectData)) {
					return
				}
				selectData.forEach((item) => {
					item.id = 'assignee_' + item.id
				})
				param.initiatorSelectData = JSON.stringify(selectData)
			}
			// 这里直接换成草稿中的模型id就行
			if (openType.value === 'DRAFT') {
				param.modelId = recordData.value.modelId
			}
			// 调用接口发起流程
			processMyApi
				.processStart(param)
				.then(() => {
					// 判断如果是草稿打开后发起，那么咱们给个请求删了这个草稿
					if (openType.value === 'DRAFT') {
						const deleteParam = [
							{
								id: recordData.value.id
							}
						]
						processMyApi.processDeleteDraft(deleteParam).then(() => {
							onClose()
							emit('successful')
						})
					} else {
						message.success('操作成功')
						onClose()
					}
				})
				.finally(() => {
					buttonSpinning.valueOf = false
				})
		} catch (e) {
			message.warning('发起流程错误：' + e)
			buttonSpinning.valueOf = false
		}
	}
	// 职位选择回调，这里回调后发起流程
	const userPosChange = (record) => {
		// 选好之后，他肯定只能选择一个职位，此时我们直接将其发起
		startProcess(record)
	}
</script>
<style lang="less" scoped>
	.xn-start-process-card {
		margin-left: 100px;
		margin-right: 100px;
	}
	.xn-start-process-button {
		text-align: center;
	}
</style>
